package com.example.shudi.sdkdemo.fragment;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Fragment;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shudi.sdkdemo.R;
import com.example.shudi.sdkdemo.utils.CameraUtils;
import com.example.shudi.sdkdemo.view.CustomDialog;
import com.xs.tf.lib.Constants;
import com.xs.tf.lib.callback.IDetectListener;
import com.xs.tf.lib.XiangshiTechSDK;
import com.xs.tf.lib.callback.IEmotListener;
import com.xs.tf.lib.model.DetectParams;
import com.xs.tf.lib.model.DetectionResult;
import com.xs.tf.lib.model.Recognition;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static android.support.v4.content.ContextCompat.checkSelfPermission;

/**
 * 表情识别
 */
public class EmotFragment extends Fragment
        implements View.OnClickListener, CustomDialog.IClickInterface {
    private static final int PICTURE_REQUEST_CODE = 911;
    public static final int PERMISSIONS_REQUEST = 1;
    private ImageView ivAddPic;
    private TextView tvStartDetect;
    private ImageView ivProgress;
    private int type = 0;// 0:相机  1：图库
    private ObjectAnimator animator;
    private Bitmap bitmap;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detect, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        tvStartDetect = view.findViewById(R.id.tv_start_detect);
        ivProgress = view.findViewById(R.id.iv_progress);
        ivAddPic = view.findViewById(R.id.iv_add_pic);
        tvStartDetect.setOnClickListener(this);
        ivAddPic.setOnClickListener(this);

        animator = ObjectAnimator.ofFloat(ivProgress, "rotation", 0, 360);
        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.setDuration(1000);
        animator.setRepeatCount(1000);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.iv_add_pic:
                CustomDialog.getInstance().show(getActivity().getFragmentManager(), "CustomDialog");
                CustomDialog.getInstance().setiClickInterface(this);
                break;
            case R.id.tv_start_detect:
                if (bitmap == null) {
                    Toast.makeText(getActivity(), "请先添加图片", Toast.LENGTH_LONG).show();
                    return;
                }
                ivProgress.setVisibility(View.VISIBLE);
                tvStartDetect.setText("检测中...");
                animator.start();
                if (bitmap != null) {
                    XiangshiTechSDK.getInstance().startDetect(bitmap, new IDetectListener() {
                        @Override
                        public void onDetectResult(List<Recognition> result) {
                            ivProgress.setVisibility(View.GONE);
                            animator.cancel();
                            if (result.size() == 0) {
                                tvStartDetect.setText("检测失败");
                                return;
                            }
                            if (result.get(0).getTitle().equals("face") &&
                                    result.get(0).getConfidence() >= Constants.CONFIDENCE_TF_OD_API) {
                                DetectParams params = new DetectParams();
                                params.setBitmap(bitmap);
                                params.setRectF(result.get(0).getLocation());
                                XiangshiTechSDK.getInstance().startEmot(params, new IEmotListener() {
                                    @Override
                                    public void onEmotResult(DetectionResult result) {
                                        tvStartDetect.setText(result.getEmotionStr());
                                    }
                                });
                            }
                        }
                    });
                }
                break;
        }
    }

    @Override
    public void iOnClick(int viewId) {
        CustomDialog.getInstance().dismiss();
        switch (viewId) {
            case R.id.tv_take_photo:
                type = 0;
                detection();
                break;
            case R.id.tv_take_pic:
                type = 1;
                detectPic();
                break;
        }
    }

    public void detection() {

        if (hasPermission()) {
            CameraUtils.takePhoto(getActivity());
        } else {
            requestPermission();
        }
    }

    private boolean hasPermission() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
                checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
                        checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) ||
                    shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(getActivity(),
                        "Camera AND storage permission are required for this app", Toast.LENGTH_LONG).show();
            }
            requestPermissions(new String[]{Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(
            final int requestCode, final String[] permissions, final int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                if (type == 0) {
                    CameraUtils.takePhoto(getActivity());
                } else {
                    takePic();
                }
            } else {
                requestPermission();
            }
        }
    }


    public void detectPic() {
        if (hasPermission()) {
            takePic();
        } else {
            requestPermission();
        }

    }

    public void takePic() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, PICTURE_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            tvStartDetect.setText("开始检测");
            if (requestCode == PICTURE_REQUEST_CODE) {
                // 处理选择的图片
                handleInputPhoto(data.getData());
            } else if (requestCode == CameraUtils.REQUEST_TAKE_PICTURE) {
                File file = new File(CameraUtils.getPhotoFilePath());
                if (file.exists()) {
                    bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                    ivAddPic.setImageBitmap(bitmap);
                }
            }
        }
    }

    /**
     * 处理图片
     *
     * @param imageUri
     */
    private void handleInputPhoto(Uri imageUri) {
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
            ivAddPic.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
